<template>
    <div>
        <hd-tab :tabs="tabs"/>
        <el-form :model="form" ref="form" label-width="80px" :inline="false" size="normal">
            <el-card shadow="always" :body-style="{ padding: '20px' }">
                <div slot="header">
                    套餐资料
                </div>
                <el-form-item label="套餐名称">
                    <el-input v-model="form.title"></el-input>
                    <hd-error name="title"/>
                </el-form-item>
            </el-card>
            <el-card shadow="always" :body-style="{ padding: '20px' }" class="mt-3">
                <div slot="header">
                    模块选择
                </div>
                <hd-module-list :modules="modules" #default="{module}">
                    <el-button type="primary" size="mini" v-if="module.selected" @click="module.selected = false">取消选择
                    </el-button>
                    <el-button type="info" size="mini" v-else @click="module.selected = true"> 选择模块</el-button>
                </hd-module-list>
            </el-card>
            <el-button type="primary" @click="onSubmit" class="d-block mt-3">
                保存资料
            </el-button>
        </el-form>
    </div>
</template>

<script>
    import tabs from './tabs'

    const form = {title: '', modules: []}
    export default {
        route: false,
        props: ['id'],
        data() {
            return {tabs, form, modules: []}
        },
        async created() {
            if (this.id) this.form = await this.axios.get(`package/${this.id}`)
            const modules = await this.axios.get(`module/installed`)
            modules.map(module => {
                module.selected = this.form.modules.some(m => m.id == module.id)
            })
            this.modules = modules
        },
        methods: {
            async onSubmit() {
                const url = this.id ? `package/${this.id}` : 'package'
                this.form.modules = this.modules.filter(m => m.selected).map(m => m.id)
                await this.axios[this.id ? 'put' : 'post'](url, this.form)
                this.router('system.package.index')
            }
        }
    }
</script>

<style></style>
